package org.apache.dolphinscheduler.api.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.service.RechargeApplyService;
import org.apache.dolphinscheduler.api.utils.DateUtil;
import org.apache.dolphinscheduler.api.utils.PageInfo;
import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.dao.entity.RechargeApply;
import org.apache.dolphinscheduler.dao.entity.User;
import org.apache.dolphinscheduler.dao.mapper.RechargeApplyMapper;
import org.apache.dolphinscheduler.dao.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

@Service
public class RechargeApplyServiceImpl extends ServiceImpl<RechargeApplyMapper, RechargeApply> implements RechargeApplyService {
	
	@Autowired
	private UserMapper userMapper;

	public Result<Object> saveRechargeApply(User loginUser, RechargeApply ra) {
		Result<Object> result = new Result<>();
		ra.setUserId(loginUser.getId());
		ra.setApplyTime(new Date());
		ra.setStatus(0);
		ra.setApplyNo(generateNo());
		ra.setPayStatus(0);
		save(ra);
		result.setCode(Status.SUCCESS.getCode());
    	result.setMsg(Status.SUCCESS.getMsg());
        return result;
	}
	
	public Result<Object> auditRechargeApply(User loginUser, Integer id, RechargeApply ra) {
		Result<Object> result = new Result<>();
		
		RechargeApply _ra = getById(id);
		if(_ra == null) {
			result.setCode(Status.ERROR.getCode());
	    	result.setMsg(Status.ERROR.getMsg());
	        return result;
		}
		if(ra.getStatus() == null || ra.getTransferPrice() == null) {
			result.setCode(Status.ERROR.getCode());
	    	result.setMsg(Status.ERROR.getMsg());
	        return result;
		}
		_ra.setStatus(ra.getStatus());
		_ra.setTransferPrice(ra.getTransferPrice());
		_ra.setRemark(ra.getRemark());
		updateById(_ra);
		
		result.setCode(Status.SUCCESS.getCode());
    	result.setMsg(Status.SUCCESS.getMsg());
        return result;
	}
	
	public Result<Object> queryAllRechargeApply(User loginUser, Integer pageNo, Integer pageSize, String userName, String beginTime, String endTime) {
		Result<Object> result = new Result<>();
		QueryWrapper<RechargeApply> qw = new QueryWrapper<RechargeApply>();
		if(StringUtils.isNotBlank(beginTime)) {
			Date beginDate = DateUtil.formatDate(beginTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
			qw.ge("apply_time", beginDate);
		}
		if(StringUtils.isNotBlank(endTime)) {
			Date endDate = DateUtil.formatDate(endTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
			qw.le("apply_time", endDate);
		}
		if(loginUser.getRoleId() != null && loginUser.getRoleId() != 1) {
			qw.eq("user_id", loginUser.getId());
		}
		if(StringUtils.isNotBlank(userName)) {
			List<Integer> userIds = getUserIdByUserName(userName);
			if(userIds.size() > 0) {
				qw.in("user_id", userIds);
			} else {
				qw.isNull("user_id");
			}
		}
		qw.orderByDesc("apply_time");
		Page<RechargeApply> page = new Page<>(pageNo, pageSize);
		page = page(page, qw);
		if(page.getRecords() != null && page.getRecords().size() > 0) {
			for(RechargeApply ra : page.getRecords()) {
				if(ra.getUserId() != null) {
					User user = userMapper.selectById(ra.getUserId());
					ra.setUserName(user != null ? user.getUserName() : "");
				}
			}
		}
		PageInfo<RechargeApply> pageInfo = new PageInfo<>(pageNo, pageSize);
        pageInfo.setTotal((int) page.getTotal());
        pageInfo.setTotalList(page.getRecords());
        result.setData(pageInfo);
        
        result.setCode(Status.SUCCESS.getCode());
    	result.setMsg(Status.SUCCESS.getMsg());
        return result;
	}
	
	private String generateNo() {
		return DateUtil.getNowYYYYMMDDHHmmss() + RandomStringUtils.random(6, '1','2','3','4','5','6','7','8','9','0');
	}
	
	private List<Integer> getUserIdByUserName(String userName){
		QueryWrapper<User> qw = new QueryWrapper<User>();
		qw.like("user_name", "%" + userName + "%");
		qw.eq("state", 1);
		List<Integer> userIds = new ArrayList<Integer>();
		List<User> list = userMapper.selectList(qw);
		if(list != null && list.size() > 0) {
			list.forEach(u -> {
				userIds.add(u.getId());
			});
		}
		return userIds;
	}
}
